<template>
  <div class="login">
    <div class="mylogin" align="center">
      <h4>登录</h4>
      <el-form :model="loginForm" :rules="loginRules" ref="loginForm" label-width="25px"
               @keyup.enter.native="submitForm('loginForm')">
        <el-form-item label="" prop="account" style="margin-top: 10px;">
          <el-row>
            <el-col :span="2"><span class="el-icon-s-custom"></span></el-col>
            <el-col :span="22">
              <el-input class="inps" placeholder="账号/邮箱" v-model="loginForm.account" clearable></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="" prop="passWord">
          <el-row>
            <el-col :span="2"><span class="el-icon-lock"></span></el-col>
            <el-col :span="22">
              <el-input :show-password="true" class="inps" type="password" placeholder="密码" v-model="loginForm.passWord"
                        clearable></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="" prop="vertification">
          <el-row>
            <el-col :span="2"><span class="el-icon-lock"></span></el-col>
            <el-col :span="22">
              <el-input class="inps" type="text" placeholder="请输入下方验证码" v-model="loginForm.vertification"
                        clearable></el-input>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="" prop="">
          <el-row>
            <el-col :span="2"><span class="el-icon-lock"></span></el-col>
            <el-col :span="22">
              <el-input @click="activeVertificationCode()" class="inps" type="text" v-model="vertificationCode"
                        placeholder="此处是验证码" readonly></el-input>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item style="margin-top: 45px">
          <el-button type="primary" round class="submitBtn" @click="submitForm('loginForm')">登录</el-button>
        </el-form-item>
        <el-divider/>
        <div class="unlogin">
          <el-button text @click="forgetVisible = true" style="color: cadetblue;">忘记密码?</el-button>
          <el-dialog v-model="forgetVisible" title="忘记密码" width="450">
            <el-form :model="forgetForm" :rules="registerRules" ref="forgetForm">
              <el-form-item v-if="inputVisible" label="注册邮箱" prop="email">
                <el-input v-model="forgetForm.email" clearable/>
              </el-form-item>

              <el-form-item v-if="!inputVisible" label="用户账号" prop="account">
                <el-input v-model="forgetForm.account" clearable/>
              </el-form-item>
            </el-form>

            <template #footer>
							<span class="dialog-footer">
								<el-button @click="forgetVisible = false">取消</el-button>
								<el-button :loading="buttonSending" type="primary"
                           @click="forgetPassword('forgetForm')">找回密码</el-button>

							</span>
            </template>
            <span>
							<el-button type="info" @click="inputVisible = !inputVisible" v-if="!inputVisible">使用用户邮箱验证</el-button>
							<el-button type="info" @click="inputVisible = !inputVisible" v-else="inputVisible">使用用户账号验证</el-button>
						</span>
          </el-dialog>
          |
          <el-button text :loading="buttonSending" @click="registerVisible = true" style="color: darkkhaki">注册账号
          </el-button>

          <el-dialog v-model="registerVisible" title="注册界面" width="450">
            <el-form :model="registerForm" :rules="registerRules" ref="registerForm"
                     @keyup.enter.native="doRegister('registerForm')">
              <el-form-item label="注册邮箱" prop="email">
                <el-input class="inps" v-model="registerForm.email" clearable/>
              </el-form-item>
              <el-form-item label="登录密码" prop="password">
                <el-input v-model="registerForm.password" clearable/>
              </el-form-item>
              <el-form-item label="邮箱验证码" prop="mailCode">
                <el-input
                    disabled
                    v-if="checkMailCode"
                    placeholder="获得验证码>>>"
                    style="width: 59%; padding-right: 5%;"
                    v-model="registerForm.mailCode"
                    clearable
                />
                <el-input v-else style="width: 55%; padding-right: 10%;" placeholder="请输入验证码"
                          v-model="registerForm.mailCode" clearable/>

                <el-button v-if="checkMailCode" type="primary" @click="sendMailCode('registerForm')">获取验证码</el-button>
                <el-button v-else :disabled="!checkMailCode" type="primary" @click="sendMailCode">{{
                    countMessage
                  }}
                </el-button>
              </el-form-item>

              <el-form-item label="选择性别" prop="sex">
                <div class="mb-2 flex items-center text-sm">
                  <el-radio-group v-model="registerForm.sex" class="ml-4">
                    <el-radio label="男" size="large">男</el-radio>
                    <el-radio label="女" size="large">女</el-radio>
                  </el-radio-group>
                </div>
              </el-form-item>
            </el-form>
            <template #footer>
							<span class="dialog-footer">
								<el-button @click="registerVisible = false">取消</el-button>
								<el-button :loading="buttonSending" :disabled="registerCount >= 4" type="primary"
                           @click="doRegister('registerForm')">立即注册</el-button>
							</span>
            </template>
          </el-dialog>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import {mapMutations} from 'vuex';
import {doForget, doLogin, getRandomCode, sendMailCode, toRegister} from '@/api/common';
import {getTaskCount} from '@/api/task';
import {ElMessage} from 'element-plus';

export default {
  name: 'Login',
  data: function () {
    return {
      verification: '',
      verificationResult: '',
      vertificationCode: '',

      buttonSending: false,

      checkMailCode: true,
      countDown: 180,
      registerCount: 0,
      countMessage: 'Waiting...',

      registerVisible: false,
      forgetVisible: false,
      inputVisible: true,
      registerForm: {
        password: '',
        sex: '',
        email: '',
        mailCode: ''
      },
      forgetForm: {
        email: '',
        account: ''
      },
      loginForm: {
        account: '',
        passWord: '',
        vertification: ''
      },
      loginRules: {
        account: [
          {
            required: true,
            message: '请输入账号或邮箱',
            trigger: 'blur'
          }
        ],
        passWord: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ],
        vertification: [
          {
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
          }
        ]
      },
      registerRules: {
        account: [
          {
            required: true,
            message: '请输入账号',
            trigger: 'change'
          },
          {
            required: true,
            pattern: /^[A-Za-z0-9]+$/,
            message: '用户账号仅允许输入[数字，及字母大小写]',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'change'
          },
          {min: 8, message: '长度必须大于8位', trigger: 'blur'}
        ],

        sex: [
          {
            required: true,
            message: '请输入性别',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'change'
          },
          {
            required: true,
            pattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
            message: '不符合邮箱格式',
            trigger: 'blur'
          }
        ],
        mailCode: [
          {
            required: true,
            message: '请输入邮箱验证码',
            trigger: 'change'
          },
          {min: 6, max: 8, message: '验证码长度为6-8，请检查！', trigger: 'blur'}
        ]
      }
    };
  },

  methods: {
    ...mapMutations(['changeLogin']),
    sendMailCode(formName) {
      this.$refs.registerForm.validateField(['email', 'password'], valid => {
        if (valid) {
          this.checkMailCode = false;
          sendMailCode(this.registerForm).then(resp => {
            if (resp.success) {
              if (this.registerCount < 3) {
                ElMessage.success('验证码已发送，请在180秒内于您的邮箱查看！');
                // this.checkMailCode = 1;
                let timer = setInterval(() => {
                  if (this.countDown > 0) {
                    this.countMessage = this.countDown + 's后重试';
                    this.countDown--;
                  } else {
                    clearInterval(timer);
                    this.checkMailCode = true;
                    // this.checkMailCode = 0; // 启用按钮
                    this.countDown = 180; // 重置倒计时时间
                    this.countMessage = 'Waiting...';
                  }
                }, 1000);
                this.registerCount++;
                registerForm.mailCode = '';
              } else {
                ElMessage.error('今日尝试次数过多，此功能已被停用');
                this.countMessage = '已停用';
                this.checkMailCode = false;
                this.registerCount++;
              }
            } else {
              this.checkMailCode = true;
            }
          });
        } else {
          ElMessage.error('请正确输入邮箱及密码信息！');
        }
      });
    },
    doRegister(registerForm) {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.buttonSending = true
          const registerData = {
            password: this.registerForm.password,
            email: this.registerForm.email,
            sex: this.registerForm.sex
          };
          const mailCode = this.registerForm.mailCode;
          //此处放进注册方法
          toRegister(registerData, mailCode).then(resp => {
            if (resp.success) {
              //注册成功后应该弹出验证码输入框
              this.registerVisible = false;
              this.loginForm.account = registerData.email;
              this.loginForm.passWord = registerData.password;
              this.$message({
                type: 'success',
                message: '已注册，您已经可以登录'
              });
            }
            // else {
            // 	this.$message({
            // 		type: 'error',
            // 		message: resp.message
            // 	});
            // }
          });
          this.buttonSending = false
          // .catch(ex => {
          // 	this.$message({
          // 		type: 'error',
          // 		message: ex.message
          // 	});
          // });
        }
      });
    },
    submitForm(formInfo) {
      this.$refs[formInfo].validate(valid => {
        if (valid) {
          this.buttonSending = true
          const data = {
            account: this.loginForm.account,
            password: this.loginForm.passWord,
            vertification: this.loginForm.vertification
          };
          if (data.vertification != this.verificationResult) {
            this.$message({
              type: 'error',
              message: '验证码不正确，请重新输入'
            });
            this.buttonSending = false
            return;
          }

          //此处放进登录方法
          doLogin(data).then(resp => {
            if (resp.success) {
              // console.log(resp);
              window.sessionStorage.setItem('token', resp.data.token);
              window.sessionStorage.setItem('user', JSON.stringify(resp.data.user));

              getTaskCount().then(resp => {
                window.sessionStorage.setItem('receiveCount', resp.data.receiveCount);
                window.sessionStorage.setItem('publishCount', resp.data.publishCount);
              });
              //3.做路由的转发
              if (resp.data.user.role != 0) {
                this.$router.push('/home/index');
              } else {
                this.$router.push('/layout');
              }
            }
          });
          this.buttonSending = false
        }
      });
    },
    forgetPassword(formInfo) {
      this.$refs[formInfo].validate(valid => {
        if (valid) {
          this.buttonSending = true
          const data = {
            email: this.forgetForm.email,
            account: this.forgetForm.account
          };
          //此处放入忘记密码方法
          doForget(data).then(resp => {
            if (resp.success) {
              this.$message({
                type: 'success',
                message: '邮件已发送，请注意查收'
              });
            }
          });
          this.buttonSending = false
        }
      });
    },
    activeVertificationCode() {
      getRandomCode().then(resp => {
        this.vertificationCode = resp.data.code + '  ' + '（点击刷新）';
        this.verificationResult = resp.data.result;
        // console.log(this.verificationResult);
        // console.log(resp);
      });
    }
  },
  mounted() {
    this.activeVertificationCode();
  }
};
</script>
<style scope>



.el-button--text {
  margin-right: 15px;
}

.el-select {
  width: 300px;
}

.el-input {
  width: 300px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

body {
  margin: 0px;
}

.login {
  width: 100vw;
  padding: 0;
  margin: 0;
  height: 100vh;
  font-size: 16px;
  background-position: left top;
  background-color: #363968;
  color: #fff;
  font-family: 'Source Sans Pro';
  position: relative;
}

.mylogin {
  width: 240px;
  height: 400px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  padding: 50px 60px 50px 60px;
  box-shadow: -15px 15px 15px rgba(6, 17, 47, 0.7);
  opacity: 1;
  background: linear-gradient(230deg, rgba(53, 57, 74, 0) 0%, rgb(0, 0, 0) 100%);
}

.inps input {
  border: none;
  color: #000000;
  background-color: transparent;
  font-size: 12px;
}

.submitBtn {
  background-color: transparent;
  color: #39f;
  width: 200px;
}
</style>
